package com.letv.ads.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.letv.android.sdk.R;
import com.letv.android.client.task.base.LetvAsyncTask;
import com.letv.core.db.PreferencesManager;

public class ApkDownloadAsyncTask extends LetvAsyncTask<Integer, Void> {

    private int notificationId;
    private static NotificationManager notificationManager;

    private Context mContext;
    private String url;
    public int startPosition = 0;
    public int progress;
    private int oldProgress;
    private String appName;
    private String path;
    private Notification notification;
    private boolean flag = true;
    private String apkNameCn;
    private CallBack callback;

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    if (!flag) return;
                    notification.contentView.setProgressBar(R.id.progress_value, 100, progress, false);
                    notification.contentView.setTextViewText(R.id.progress_text, progress + "%");
                    notificationManager.notify(notificationId, notification);
                    break;
                case 1:
                    if (!flag) return;
//                    下载完成，保存liteApp的相关配置  by pangzhen
                    PreferencesManager mPreferencesManager = PreferencesManager.getInstance();
                    mPreferencesManager.setLiteDownloadCompleted();
                    mPreferencesManager.setLiteDownLoadName(appName);
                    mPreferencesManager.setLiteDownLoadPath(path);

                    notificationManager.cancel(notificationId);
                    notification.icon = R.drawable.letv_notification01;
                    notification.tickerText = "下载完成";// mContext.getString(R.string.update_finish);
                    notification.contentView.setProgressBar(R.id.progress_value, 100, 100, false);
                    notification.contentView.setViewVisibility(R.id.app_name, View.GONE);
//                mContext.getString(R.string.update_finish_install)
                    notification.contentView.setTextViewText(R.id.progress_text,
                            apkNameCn + " " + "下载完成，点击安装");
                    notification.contentView.setViewVisibility(R.id.progress_value, View.GONE);
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    String type = "application/vnd.android.package-archive";
                    File file = new File(path + "/" + appName);
                    intent.setDataAndType(Uri.fromFile(file), type);
                    mContext.startActivity(intent);
//                    mContext.finish();
                    break;
            }
        }

    };

    public ApkDownloadAsyncTask(Context context, String url, String apkNameCn, int notificationId, CallBack callback) {
        this.url = url;
        this.apkNameCn = TextUtils.isEmpty(apkNameCn) ? "未知软件" : apkNameCn;
        this.callback = callback;
        this.mContext = context;
        this.notificationId = notificationId;
        // appName = url.substring(url.lastIndexOf("/"), url.length());
        // if (!appName.contains(".apk")) {
        // appName += ".apk";
        // }

        appName = System.currentTimeMillis() + ".apk";


        if (null == notificationManager) {
            notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        }
        this.notification = new Notification();
    }

    @Override
    protected Void doInBackground() {

        URL uRL = null;
        HttpURLConnection httpURLConnection = null;
        InputStream inputStream = null;
        FileOutputStream outputStream = null;

        /**
         * 如果有SD卡就保存在SD卡，否则保存到内存中
         * */
         if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            path = mContext.getDir("updata", Context.MODE_WORLD_WRITEABLE | Context.MODE_WORLD_READABLE | Context.MODE_PRIVATE)
                    .getPath();
        } else {
            path = Environment.getExternalStorageDirectory().getPath();
        }

        int length = 0;
        try {
            uRL = new URL(this.url);
            httpURLConnection = (HttpURLConnection) uRL.openConnection();
            // httpURLConnection.setRequestProperty("Accept-Encoding",
            // "identity");
            // httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setInstanceFollowRedirects(false);
            // httpURLConnection.setDoInput(true);
            // httpURLConnection.setDoOutput(true);
            httpURLConnection.setConnectTimeout(5000);
            httpURLConnection.setAllowUserInteraction(true);
            httpURLConnection.connect();
            int respCode = httpURLConnection.getResponseCode();
            if (302 == respCode) {
                url = httpURLConnection.getHeaderField("Location");
                uRL = new URL(url);
                httpURLConnection = (HttpURLConnection) uRL.openConnection();
                httpURLConnection.setRequestMethod("GET");
                httpURLConnection.setConnectTimeout(5000);
            }

            length = httpURLConnection.getContentLength();

            inputStream = httpURLConnection.getInputStream();
            File file = new File(path + "/" + appName);

            if (file.exists() && file.isFile()) {
                file.delete();
            }
            outputStream = new FileOutputStream(file);
            // outputStream.seek(startPosition);

            byte[] buf = new byte[1024 * 1024];
            int read = 0;
            int curSize = startPosition;

            while (flag) {
                publishProgress(progress);
                read = inputStream.read(buf);
                if (read == -1) {
                    publishProgress(progress);
                    break;
                }
                outputStream.write(buf, 0, read);
                curSize = curSize + read;

                progress = (int) (curSize * 100f / length);

                if (curSize >= length) {
                    progress = 100;
                    publishProgress(progress);
                    break;
                }
            }
            inputStream.close();
            outputStream.close();
            httpURLConnection.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void close() {
        flag = false;
        if (notificationManager != null) {
            notificationManager.cancel(this.notificationId);
        }
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

        // 系统权限写入
        if (progress == 100) {
            if (null != callback) {
                callback.Success();
            }
            String[] command = {"chmod", "777", path + "/" + appName};
            ProcessBuilder builder = new ProcessBuilder(command);
            try {
                builder.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
            handler.sendEmptyMessage(1);
        } else {
            if (null != callback) {
                callback.Failed();
                close();
                Toast.makeText(this.mContext, "文件下载失败",Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Intent intent = new Intent();

        PendingIntent pendingIntent = PendingIntent.getActivity(this.mContext, 0, intent, 0);

        this.notification.icon = R.anim.letv_notification_download;
        this.notification.tickerText = "正在下载";//mContext.getResources().getString(R.string.update_asynctask_downloading);
        this.notification.flags = Notification.FLAG_AUTO_CANCEL;
        RemoteViews remoteViews = new RemoteViews(mContext.getPackageName(), R.layout.letv_notification_updata_layout);
        remoteViews.setTextViewText(R.id.app_name, "【乐视软件推荐】下载 " + apkNameCn);
        remoteViews.setTextViewText(R.id.progress_text, "0%");
        remoteViews.setProgressBar(R.id.progress_value, 100, 0, false);
        this.notification.contentView = remoteViews;
        this.notification.contentIntent = pendingIntent;
        notificationManager.notify(notificationId, notification);
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        if (this.notification != null) {
            if (progress > oldProgress + 2) {
                oldProgress = progress;
                handler.sendEmptyMessage(0);
            }
        }
        super.onProgressUpdate(values);
    }

    public interface CallBack {

        void Success();

        void Failed();
    }

    /**
     * 下载中的任务
     */
    private static HashSet<String> runningSet;

    static {
        runningSet = new HashSet<String>();
    }

    public static int NOTIFICATION_ID = 112233;
    public static ArrayList<ApkDownloadAsyncTask> NOTIFICATION_ID_LIST = new ArrayList<ApkDownloadAsyncTask>();

    public static void downloadApk(final Context context, final String url, String apkNameCn) {
        if (url == null || url.length() <= 0 || context == null) {
            return;
        }
        final String realUrl = getQueryString(url,"u");
        synchronized (runningSet) {
            if(runningSet.size() > 10){
                return;
            }
            if (!runningSet.contains(realUrl)) {
                runningSet.add(realUrl);

                ApkDownloadAsyncTask downloadAsyncTask = new ApkDownloadAsyncTask(context, url, apkNameCn, NOTIFICATION_ID, new CallBack() {
                    @Override
                    public void Success() {
                        runningSet.remove(realUrl);
                    }

                    @Override
                    public void Failed() {
                        runningSet.remove(realUrl);
                    }
                });

                downloadAsyncTask.execute();

                NOTIFICATION_ID_LIST.add(downloadAsyncTask);

                NOTIFICATION_ID++;
                //mContext.getResources().getString(R.string.recommend_apk_download_info)
                Toast.makeText(context, "添加下载文件成功",
                        Toast.LENGTH_SHORT).show();
            } else {
//                mContext.getResources().getString(R.string.recommend_apk_downloading_info),
                Toast.makeText(context, "文件正在下载中",
                        Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 清楚所有通知
     */
    public static void clearNotifys() {
        for (ApkDownloadAsyncTask downloader : NOTIFICATION_ID_LIST) {
            downloader.close();
        }
    }
    private static String getQueryString(String url,String key){
        try {
            if(TextUtils.isEmpty(url))
                return url;
            Uri uri = Uri.parse(url);
            return uri.getQueryParameter(key);
        } catch (Exception e) {
        }
        return url;
    }

}
